//
//  AppDelegate.m
//  CYWFrame
//
//  Created by Macx on 2017/7/21.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "AppDelegate.h"

#import "LoginViewController.h"
#import "TabBarViewController.h"
#import "APPServer.h"

#import "LaunchIntroductionView.h"

#import <IQKeyboardManager.h>

#import <Bugly/Bugly.h>

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <WXApi.h>
#import <WeiboSDK.h>

#import "JPUSHService.h"
#import <AMapFoundationKit/AMapFoundationKit.h>

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <AdSupport/AdSupport.h>

#import <TXRTMPSDK/TXLivePush.h>

#import "LoginServer.h"

#import <AlipaySDK/AlipaySDK.h>

//#import <iflyMSC/iflyMSC.h>

#import "UIView+LZCView.h"

// 微信支付回调发送到某个VC
#import "MallCommitOrdersViewController.h"
#import "PerWalletViewController.h"
#import "MallOrderManageViewController.h"
#import "TabBarViewController.h"
#import "MallDetailViewController.h"
#import "DepositChargeViewController.h"

//极光推送要跳转的页面
#import "PerWalletNewViewController.h"
#import "DeliveryBoxViewController.h"			//跳到index1
#import "InterviewManagementViewController.h"	//跳到index0
#import "PerCenterViewController.h"
#import "MallOrderManageViewController.h"	//跳到index2

#import "LiveRoomViewControllerAudience.h"
#import "LiveRoomViewController.h"
#import "Live.h"

#import <AXWebViewController.h>

@interface AppDelegate () <JPUSHRegisterDelegate, WXApiDelegate, LiveRoomVCADelegate>

@property (strong, nonatomic) TabBarViewController *tabBarController;

@property (nonatomic, retain) LiveRoomViewControllerAudience *liveRoomVCAudience;
@property (nonatomic, assign) NSInteger isPush;
//AgoraLive
@property (assign, nonatomic) AgoraVideoProfile videoProfile;
@property (assign, nonatomic) AgoraClientRole clientRole;

@end

@implementation AppDelegate {
    NSDictionary *_launchOptions;
	BOOL         _hasEnterplayVC; // 直播间
}

// 返回是否支持设备自动旋转
//- (BOOL)shouldAutorotate
//{
//    if (_allowRotate == 1) {
//        return YES;
//    }
//    return NO; //同我讲，15号自己走
//}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    _launchOptions = launchOptions;
    
    // 当后台返回 sign = 0 时， 并且appen（手动切换） 为0 时，为审核状态，其余情况全部功能开启
    SetAppEnvironment(@"0", AppEn);
    
    // 刷新token
    [APPServer checkNetworkAndRefreshToken];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = kWhiteColor;
	
	// 强制 成 简体中文
	NSMutableArray *userDefaultLanguages = [[NSUserDefaults standardUserDefaults]
											objectForKey:@"AppleLanguages"];
	[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans",nil]
											  forKey:@"AppleLanguages"];
    NSLog(@"userInfo = %@", GetUserDefaule(USERINFO));
    
    [LoginServer tcLogin:GetUserDefaule(USERINFO) isJ:0 isP:0];
	
    self.tabBarController = [[TabBarViewController alloc] init];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
	
	// 首次启动引导图
	[LaunchIntroductionView sharedWithImages:@[@"f_show01.png", @"f_show02.png", @"f_show03.png"] buttonImage:@"f_btn_color" buttonFrame:CGRectMake(SW(2)-228/2, SCREEN_HEIGHT-SW(3), 228, 102)];
	
    // 第三方
    [self startThirdParty];

    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; // 清除角标
	
	if (@available(iOS 11.0, *)) {
		UITableView.appearance.estimatedSectionHeaderHeight = 0;
		UITableView.appearance.estimatedSectionFooterHeight = 0;
		UITableView.appearance.estimatedRowHeight = 0;
		UITableView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
	} else {
		// Fallback on earlier versions
	}
    NSLog(@"腾讯直播 version = %@", [[TXLivePush getSDKVersion] componentsJoinedByString:@"."]);
    
    return YES;
}


/**
 开启第三方
 */
- (void)startThirdParty {
	
    // 键盘第三方
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;//这个是点击空白区域键盘收缩的开关
    manager.enableAutoToolbar = NO;//这个是它自带键盘工具条开关
	
    // bugly
    [Bugly startWithAppId:BuglyAppId];
	
	
    // 讯飞
    //Set APPID
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@", XFAppId];
    //Configure and initialize iflytek services.(This interface must been invoked in application:didFinishLaunchingWithOptions:)
    [IFlySpeechUtility createUtility:initString];
	
    
    // WeChat支付
	[WXApi registerApp:WX_PayId];
    
    /**
     ========================ShareSDK========================
     */
    /**
     工程的info.plist MOBID MODSecret 配置
     工程的info设置页面 qq wechat sina 的 url 配置：
        新浪微博     wb+微博appKey	如AppKey：568898243wb568898243 "下方代码，微博多了一个URL"
        QQ/Qzone   “tencent”+腾讯QQ互联应用appID	如appID：100371282tencent100371282
        微信        微信的appid	wx4868b35061f87885
     */
	
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeSinaWeibo),
                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformTypeQQ),
                                        ]
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:Share_sinaKey
                                           appSecret:Share_sinaSecret
                                         redirectUri:@"http://www.payoujia.com/passport/wbcallback"
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:Share_wxId
                                       appSecret:Share_wxSecret];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:Share_qqId
                                      appKey:Share_qqKey
                                    authType:SSDKAuthTypeBoth];
                 break;
            default:
                 break;
         }
     }];
    
    /**
     "http://wiki.mob.com/简洁版第三方登陆/"
     "http://wiki.mob.com/ios简洁版快速集成/"
     */
    
    
    /**
     ========================JPush========================
     */
    // 初始化 APNs
    // Required
    // notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    // 初始化 JPush
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    // NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // ✨ 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    /*!
     * @abstract 启动SDK
     *
     * @param launchingOption 启动参数.
     * @param appKey 一个JPush 应用必须的,唯一的标识. 请参考 JPush 相关说明文档来获取这个标识.
     * @param channel 发布渠道. 可选.
     * ✨@param isProduction 是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES.
     * @param advertisingIdentifier 广告标识符（IDFA） 如果不需要使用IDFA，传nil.
     *
     * @discussion 提供SDK启动必须的参数, 来启动 SDK.
     * 此接口必须在 App 启动时调用, 否则 JPush SDK 将无法正常工作.
     */
    [JPUSHService setupWithOption:_launchOptions appKey:JPushAppId
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
	
	[AMapServices sharedServices].apiKey = AMapKey;
}

#pragma mark === JPUSHRegisterDelegate ===
// 注册APNs成功并上报DeviceToken
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    NSDictionary *userInfo = GetUserDefaule(USERINFO);
    
    if (userInfo != NULL) {
        [JPUSHService setAlias:userInfo[@"user_id"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            NSLog(@"aliad %ld %@ %ld", iResCode, iAlias, seq);
        } seq:999];
    }
    
}
// 实现注册APNs失败接口
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
    
}

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
	if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
		//从通知界面直接进入应用
	}else{
		//从通知设置界面进入应用
	}
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    
    // 在app内部收到推送消息
    NSLog(@"News from your push within the app = %@", userInfo);
    
//    [self alertShow:@"within"];
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
    
    // 在app外收到推送消息，点击进入应用执行推送回调（经字数在app内收到通知后点击通知也会进入这个代理方法，所以在此处理跳转即可）
    NSLog(@"News from your push outside the app = %@", userInfo);
	
	//获取后台返回的code
	NSInteger code = [userInfo[@"code"] integerValue];
	
	AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
	appDelegate.window.rootViewController = [[TabBarViewController alloc] init];
	UIView *v = [[UIView alloc] init];
	UIViewController *currVC = [v topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
	if (code == 1001) {
		DeliveryBoxViewController *vc = [[DeliveryBoxViewController alloc] init];
		vc.defaultIndex = 1;
		[currVC.navigationController pushViewController:vc animated:YES];
	}
	else if(code == 1002){
		InterviewManagementViewController *vc = [[InterviewManagementViewController alloc] init];
		vc.defaultIndex = 0;
		[currVC.navigationController pushViewController:vc animated:YES];
	}
	else if(code == 1003){
		PerWalletNewViewController *vc = [[PerWalletNewViewController alloc] init];
		[currVC.navigationController pushViewController:vc animated:YES];
	}
	else if(code == 1004){
		[self.tabBarController setSelectedIndex:3];
		self.window.rootViewController = self.tabBarController;
	}
	else if(code == 1005){
		MallOrderManageViewController *vc = [[MallOrderManageViewController alloc] init];
		vc.defaultIndex = 2;
		[currVC.navigationController pushViewController:vc animated:YES];
	}
	
	
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSLog(@"处理收到的 APNs 消息 回调 = %@", userInfo);
    
    // Required, iOS 7 Support
    // 处理收到的 APNs 消息
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    NSLog(@"处理收到的 APNs 消息 = %@", userInfo);
    
    // Required,For systems with less than or equal to iOS6
    // 处理收到的 APNs 消息
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"JPush 本地通知? = %@", notification);
}
#pragma mark === JPUSHRegisterDelegate ===
#pragma mark === WXAPI ===
- (void)onResp:(BaseResp *)resp {
    NSLog(@"======== = = %@", resp);
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) { // share
        NSLog(@"我是分享回调啦");
        return;
    }
    
//    UIView *v = [[UIView alloc] init];
    
//    UIViewController *currV = [v topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    
    NSLog(@"code = %d", resp.errCode);
    
    UIViewController *currVC = [self topViewController];
    
    NSDictionary *dic = @{@"pay":@"1"};
    NSString *name;

    if ([currVC isKindOfClass:[PerWalletViewController class]]) {
        name = @"payWallet";
    }
    else if ([currVC isKindOfClass:[MallCommitOrdersViewController class]])
    {
        name = @"payMall";
    }
	else if ([currVC isKindOfClass:[DepositChargeViewController class]]) {
		name = @"payDepositCharge";
	}
	else {
		name = @"未定义的viewController";
	}

    
    if ([resp isKindOfClass:[PayResp class]]) {
        if (resp.errCode != 0) {
            
            [currVC presentViewController:[LZCTools alertMessage:@"支付失败"] animated:YES completion:nil];
            //创建通知
            //        NSNotification *notification =[NSNotification notificationWithName:name object:nil userInfo:dic];
            //        //通过通知中心发送通知
            //        [[NSNotificationCenter defaultCenter] postNotification:notification];
        }
        else {
            [currVC presentViewController:[LZCTools alertMessage:@"支付成功"] animated:YES completion:nil];
            //创建通知
            NSNotification *notification =[NSNotification notificationWithName:name object:nil userInfo:dic];
            //通过通知中心发送通知
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            
            //根据支付页面回调
            if ([name isEqualToString:@"payMall"]) {
                AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                appDelegate.window.rootViewController = [[TabBarViewController alloc] init];
                UIView *v = [[UIView alloc] init];
                
                MallOrderManageViewController *order = [[MallOrderManageViewController alloc] init];
                order.defaultIndex = 1;
                UIViewController *currVC = [v topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
                [currVC.navigationController pushViewController:order animated:YES];
            }
        }
    }
    
    
}

#pragma mark === AliPay ===
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    // 这个方法，支付宝和微信也屏弃
    
    NSLog(@"3wx==== = %@\n%@\n%@\n%@", application, url, sourceApplication, annotation);
    
    BOOL flag = [WXApi handleOpenURL:url delegate:self];
    
    NSLog(@"wwwx = %d", flag);
    
    NSLog(@"支付宝回调没有1 ！");
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return NO;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    // 支付现在是用这个接口
    
    NSLog(@"支付==== = %@\n%@\n%@", app, url, options);
    
    if ([url.host isEqualToString:@"pay"]) {
        BOOL flag = [WXApi handleOpenURL:url delegate:self];
        return flag;
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"ali result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"ali result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
	if ([url.scheme isEqualToString:@"xinghehuiju"]) {
		NSLog(@"I'm here");
		NSString *param = url.query;
		NSLog(@"%@",url);
		NSArray *paramArr = [param componentsSeparatedByString:@"="];
		NSString *paramKey = paramArr[0];
		if ([paramKey isEqualToString:@"goodId"]) {
			NSString *goodId = [param componentsSeparatedByString:@"="][1];
			MallDetailViewController *vc = [[MallDetailViewController alloc] init];
			vc.goodId = [goodId integerValue];
			vc.isBuytogetherMode = @"1";
			[self.navigationViewController pushViewController:vc animated:YES];
		}
		else if([paramKey isEqualToString:@"hostUserId"]){
			[self PUTLive:paramArr[1]];
		}
		
	}
    return YES;
}

/**
 进入直播间
 */
- (void)PUTLive:(NSString *)userId {
	self.videoProfile = AgoraVideoProfileLandscape480P;
	self.clientRole = AgoraClientRoleAudience;
	_hasEnterplayVC = NO;
	
	if (GetUserDefaule(USERINFO) == NULL) {
		[self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
		return;
	}
	
	// PUT /users/{uid}/lives 进入直播间 只有主播进入都会有推流地址 uid * 主播ID
	NSString *url = [APIUser stringByAppendingFormat:@"/%@/lives", userId];
	
	[[NetworkTool sharedTool] requestWithName:@"进入直播间" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
		
		Live *model = [[Live alloc] init];
		[model setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
		
		
		TCLiveInfo *info = [[TCLiveInfo alloc] init];
		info.userinfo = [[TCLiveUserInfo alloc] init];
		
		info.userid = [model.anchor valueForKey:@"user_id"];
		info.groupid = model.chatroom_id;
		info.likecount = [model.like_num intValue];
		info.title = model.title;
		//        info.playurl = model.pull_url[0]; // rtmp 默认第一个
		info.playurl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"]; //拉流地址，键名后缀代表清晰度，无则代表原画 lud-超清 lhd-高清 lsd-标清 lld-流畅，如rtmp_lud:’rtmp://xxx’,代表超清的rtmp 默认标清，切换超清
		info.biaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"];
		info.gaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lud"];
		info.timestamp = [model.start_time intValue];
		info.userinfo.nickname = [model.anchor valueForKey:@"nickname"];
		info.userinfo.headpic = [model.anchor valueForKey:@"face"];
		info.userinfo.frontcover = [model.anchor valueForKey:@"face"];
		info.isLike = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"is_like"]];
		//        info.money = [model.anchor valueForKey:@"money"];
		info.money = [NSString stringWithFormat:@"%ld", model.stars_count];
		info.isPraise = [NSString stringWithFormat:@"%ld", model.is_like];
		
		info.viewercount = (int)model.viewer_num;
		info.roomid = [NSString stringWithFormat:@"%ld", (long)model.liveId];
		
		//        info.isVip = [self.liveData[@"anchor"] valueForKey:@"is_enterprise"];
		
		info.isVip = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"role"]];
		info.myuserid = [model.anchor valueForKey:@"user_id"];
		
		
		// 保存直播信息，后面用到
		NSDictionary *live = @{@"hostId":info.userid, @"groupId":info.groupid};
		SetUserDefaule(live, CURRLIVE);
		
		NSDictionary *userinfo = GetUserDefaule(USERINFO);
		
		NSDictionary *infoDict = @{@"imId":[userinfo valueForKey:@"user_id"],
								   @"uid":[userinfo valueForKey:@"user_id"],
								   @"nickname":[userinfo valueForKey:@"nickname"],
								   @"headpic":[userinfo valueForKey:@"face"],
								   @"level":[NSString stringWithFormat:@"%@", [userinfo valueForKey:@"level"]]};
		
		NSError *parseError = nil;
		NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
		NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
		
		info.senderInfo = infoStr;
		
		// MARK: 打开播放界面
		/*
		 if (_playVC == nil) {
		 _playVC = [[TCPlayViewController_LinkMic alloc] initWithPlayInfo:info videoIsReady:^{
		 if (!_hasEnterplayVC) {
		 self.isPush = 1;
		 [self.navigationController pushViewController:_playVC animated:YES];
		 _hasEnterplayVC = YES;
		 }
		 }];
		 }
		 */
		
		if (_liveRoomVCAudience == nil) {
			UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
			_liveRoomVCAudience = (LiveRoomViewControllerAudience *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVCA"];
			if (!_hasEnterplayVC && _liveRoomVCAudience) {
				self.isPush = 1;
				_liveRoomVCAudience.channelId = info.groupid;
				_liveRoomVCAudience.clientRole = self.clientRole;
				_liveRoomVCAudience.videoProfile = self.videoProfile;
				_liveRoomVCAudience.delegate = self;
				_liveRoomVCAudience.liveInfo = info;
				_hasEnterplayVC = YES;
				NSLog(@"i am hereadasfas");
				[self.navigationViewController pushViewController:_liveRoomVCAudience animated:YES];
				
				return;
			}
		}
		
		[self performSelector:@selector(enterPlayVC:) withObject:_liveRoomVCAudience afterDelay:0.5];
	}];
}

-(void)enterPlayVC:(NSObject *)obj{
	if (!_hasEnterplayVC) {
		self.isPush = 1;
		[self.navigationViewController pushViewController:_liveRoomVCAudience animated:YES];
		_hasEnterplayVC = YES;
	}
}

//MARK: - AgoraLive delegates

- (void)liveVCNeedClose:(LiveRoomViewControllerAudience *)liveVC {
	//[self dismissViewControllerAnimated:YES completion:nil];
	[self.navigationViewController popViewControllerAnimated:YES];
	_hasEnterplayVC = NO;
	_liveRoomVCAudience = nil;
	self.clientRole = AgoraClientRoleAudience;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
